package cn.ycc1.boot3redisson.service.impl;

import cn.ycc1.boot3redisson.config.CompletableTask;
import cn.ycc1.boot3redisson.service.ThreadRedissonAnnotationService;
import cn.ycc1.boot3redisson.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.concurrent.Executor;

/**
 * @author ycc
 * @date 2024/7/28
 */
@Service
@RequiredArgsConstructor
public class ThreadRedissonAnnotationServiceImpl implements ThreadRedissonAnnotationService {
    private final Executor myCompletableTaskExecutor;
    private final UserService userService;

    @Override
    public void test() {
        CompletableTask.allOf(
                myCompletableTaskExecutor,
                () -> {
                    thread1();
                },
                () -> {
                    thread2();
                }
        );
    }

    private void thread2() {
        CompletableTask.allOf(
                myCompletableTaskExecutor,
                () -> {
                    userService.updateUserRedisson(2L, 1L);
                },
                () -> {
                    userService.updateUserRedisson(2L, 2L);
                }
        );
        System.out.println("------------thread2 @redisson");
    }

    private void thread1() {
        CompletableTask.allOf(
                myCompletableTaskExecutor,
                () -> {
                    userService.updateUserRedisson(2L, 3L);
                },
                () -> {
                    userService.updateUserRedisson(2L, 4L);
                }
        );
        System.out.println("------------thread1 @redisson");
    }

    /**
     * 更新用户的字段值
     *
     * @param uid
     * @param amount
     * @return
     * @MyRedissonLock(key = "'my-lock-'+#uid")
     */
//    @Transactional
//    @MyRedissonLock
//    @MyRedissonLock(value = "my:redisson:lock", key = "#uid")
//    protected Boolean updateUser(Long uid, Long amount) {
//        User user = userService.getById(uid);
//        user.setDeptId(user.getDeptId() + amount);
//        return userService.updateById(user);
//    }
}
